#include <time.h>
#include <iostream>
#include <fstream>
#include <string>

inline unsigned long long now() {
  timespec ts;
  ::clock_gettime(CLOCK_MONOTONIC, &ts);
  return ts.tv_sec * 1000000000 + ts.tv_nsec;
}

// 使用RDTSC指令获取CPU周期数，更轻量级的时间测量方式
inline unsigned long long rdtsc() {
  unsigned int lo, hi;
  __asm__ __volatile__("rdtsc" : "=a" (lo), "=d" (hi));
  return ((unsigned long long)hi << 32) | lo;
}

// 使用RDTSCP指令获取CPU周期数（序列化版本）
inline unsigned long long rdtscp() {
  unsigned int lo, hi;
  __asm__ __volatile__("rdtscp" : "=a" (lo), "=d" (hi) :: "rcx");
  return ((unsigned long long)hi << 32) | lo;
}

// 获取CPU频率（GHz）
inline double get_cpu_frequency() {
  static double frequency = 0.0;
  if (frequency > 0.0) {
    return frequency;
  }

  // 尝试从/proc/cpuinfo获取CPU频率
  std::ifstream cpuinfo("/proc/cpuinfo");
  std::string line;
  while (std::getline(cpuinfo, line)) {
    if (line.find("cpu MHz") != std::string::npos) {
      size_t pos = line.find(":");
      if (pos != std::string::npos) {
        double freq_mhz = std::stod(line.substr(pos + 1));
        frequency = freq_mhz / 1000.0; // 转换为GHz
        break;
      }
    }
  }
  cpuinfo.close();

  // 如果无法从/proc/cpuinfo获取，则使用默认值2.0GHz
  if (frequency <= 0.0) {
    frequency = 2.0;
    std::cerr << "Warning: Could not determine CPU frequency, assuming " 
              << frequency << " GHz" << std::endl;
  }

  return frequency;
}

// 将CPU周期数转换为纳秒
inline double cycles_to_nanoseconds(unsigned long long cycles) {
  double frequency_ghz = get_cpu_frequency();
  // cycles / (cycles/ns) = ns
  return static_cast<double>(cycles) / frequency_ghz;
}

// 将CPU周期数转换为微秒
inline double cycles_to_microseconds(unsigned long long cycles) {
  return cycles_to_nanoseconds(cycles) / 1000.0;
}